package com.my.socket.nio.v33;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ZhongGang
 * at 2018/8/28 15:47
 */
public class Client {
    private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();

        int nThreads = Runtime.getRuntime().availableProcessors() * 2;
        ExecutorService executorService = Executors.newFixedThreadPool(nThreads);

        for (int i = 0; i < 10000; i++) {
            CompletableFuture.supplyAsync(() -> {
                try {
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress("127.0.0.1", 9999));
                    LOGGER.info("connect: {}", socket);
                    return socket;
                } catch (IOException e) {
                    throw new UnsupportedOperationException("Not yet implemented!");
                }
            }, executorService).thenAccept(socket -> {
                try {
                    OutputStream outputStream = socket.getOutputStream();
                    IOUtils.write("I am Alex Zhong", outputStream, "UTF-8");
                    socket.shutdownOutput();

                    InputStream inputStream = socket.getInputStream();
                    String response = IOUtils.toString(inputStream, "UTF-8");
                    socket.shutdownInput();
                    LOGGER.info("read: {}", response);
                } catch (IOException e) {
                    throw new UnsupportedOperationException("Not yet implemented!");
                }
            });
        }

        LOGGER.info("it takes {} second(s)", (System.currentTimeMillis() - start) / 1000.00);
    }
}
